package com.infore.authorityManagement.controller;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.infore.authorityManagement.entity.BusinessConstant;
import com.infore.authorityManagement.entity.PasswordVo;
import com.infore.authorityManagement.entity.SysUser;
import com.infore.authorityManagement.enums.ResultStatus;
import com.infore.authorityManagement.service.ISysUserService;
import com.infore.authorityManagement.util.Page;
import com.infore.authorityManagement.util.ResultEntity;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * @ClassName: UserController
 * @Description: 用户管理controller
 * @author 谭红波
 * @date 2017年9月6日
 */
@Api(value = "用户管理", tags = "用户管理")
@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    ISysUserService userService;


    @RequestMapping(value = "/all", method = RequestMethod.GET)
    public @ResponseBody List<SysUser> getUsers(SysUser sysUser) {
        List<SysUser> list = userService.getUsers(sysUser);
        return list;
    }

    @ApiOperation(value = "查询用户", notes = "根据用户ID来获取用户详细信息")
    @RequestMapping(value = "/id", method = RequestMethod.GET)
    public @ResponseBody ResultEntity getUserById(@RequestParam String userId) {
        SysUser user = userService.getUserById(userId);
        if (null == user) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.USER_NOT_EXIST, null);
        }
        return new ResultEntity(ResultStatus.SUCCESS, BusinessConstant.QUERY_SUCCESS).setInfo(user);
    }

    @ApiOperation(value = "查询用户", notes = "根据用户账号来获取用户详细信息")
    @RequestMapping(value = "/account", method = RequestMethod.GET)
    public @ResponseBody ResultEntity getUserByName(@RequestParam String userAccount, String token) {
        SysUser user = userService.getUserByAccount(userAccount);
        if (null == user) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.USER_NOT_EXIST, null);
        }
        return new ResultEntity(ResultStatus.SUCCESS, BusinessConstant.QUERY_SUCCESS).setInfo(user);
    }

    @ApiOperation(value = "查询用户", notes = "批量获取用户，约定：当pageSize小于1 或者 pageNo小于0或者其中一个为空时，不进行分页操作")
    @ApiImplicitParams({ @ApiImplicitParam(name = "sysUser", value = "用户信息", required = false, dataType = "SysUser"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageNo", value = "第几页", required = false, dataType = "Integer") })
    @RequestMapping(value = "", method = RequestMethod.GET)
    public @ResponseBody ResultEntity getUsers(SysUser sysUser, Integer pageSize, Integer pageNo, String token) {
        if (pageSize == null || pageNo == null || pageSize < 1 || pageNo < 0) {
            List<SysUser> list = userService.getUsers(sysUser);
            return new ResultEntity(ResultStatus.SUCCESS, BusinessConstant.QUERY_SUCCESS).setDataList(list);
        } else {
            Page<SysUser> page = userService.getUsersForPage(sysUser, pageSize, pageNo);
            return new ResultEntity(ResultStatus.SUCCESS, BusinessConstant.QUERY_SUCCESS).setPage(page);
        }

    }

    @ApiOperation(value = "新增用户", notes = "填写用户详细信息, 用户账号(user_account)、密码(password)必须填写")
    @ApiImplicitParams({ })
    @RequestMapping(value = "", method = RequestMethod.POST)
    public @ResponseBody ResultEntity addUser(SysUser sysUser, String token) {
        String account = sysUser.getUserAccount().trim();
        String password = sysUser.getPassword();
        if (StringUtils.isBlank(account) || StringUtils.isBlank(password)) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.PARAM_ERROR);
        }
        java.util.Date date = new java.util.Date();
        long dtime = date.getTime();
        Timestamp timestamp = new Timestamp(dtime);
        sysUser.setCreateTime(timestamp);
        Map<String, Object> map = userService.addUser(sysUser);
        int resultIdt = (int) map.get("resultIdt");
        if (resultIdt == -1) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.USER_EXIST);
        }
        if (resultIdt == -2) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.DATA_ERROR);
        }
        return new ResultEntity(ResultStatus.SUCCESS, BusinessConstant.INSERT_SUCCESS).setMapValue("userId",
                map.get("userId"));
    }

    @ApiOperation(value = "删除用户", notes = "根据id删除用户")
    @ApiParam(name = "userId", value = "用户ID", required = true)
    @RequestMapping(value = "/id", method = RequestMethod.DELETE)
    public @ResponseBody ResultEntity deleteUserById(@RequestParam String userId, String token) {
        int resultIdt = userService.deleteUserById(userId);
        if (resultIdt == 0) {
            return new ResultEntity(ResultStatus.SUCCESS, BusinessConstant.DELETE_SUCCESS);
        }
        return new ResultEntity(ResultStatus.ERROR, BusinessConstant.DELETE_FAILURE);
    }

    @ApiOperation(value = "删除用户", notes = "根据id删除用户")
    @ApiParam(name = "userId", value = "用户ID", required = true)
    @RequestMapping(value = "/ids", method = RequestMethod.DELETE)
    public @ResponseBody ResultEntity deleteBatchUserById(@RequestParam String ids, String token) {
        String[] array = ids.split(",");
        for (int i = 0; i < array.length; i++) {
            String userId = array[i];
            int resultIdt = userService.deleteUserById(userId);
            if (resultIdt != 0) {
                return new ResultEntity(ResultStatus.ERROR, BusinessConstant.DELETE_FAILURE);
            }
        }
        return new ResultEntity(ResultStatus.SUCCESS, BusinessConstant.DELETE_SUCCESS);

    }

    @ApiOperation(value = "删除用户", notes = "根据账号删除用户")
    @ApiImplicitParam(name = "userAccount", value = "用户账号", required = true, dataType = "String")
    @RequestMapping(value = "/account", method = RequestMethod.DELETE)
    public @ResponseBody ResultEntity deleteUserByAccount(@RequestParam String userAccount, String token) {

        int resultIdt = userService.deleteUserByAccount(userAccount);
        if (resultIdt == -1) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.USER_NOT_EXIST);
        }
        if (resultIdt == -2) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.DATA_ERROR);
        }
        return new ResultEntity(ResultStatus.SUCCESS, BusinessConstant.DELETE_SUCCESS);
    }

    @ApiOperation(value = "修改用户", notes = "修改用户信息")
    @ApiImplicitParams({ @ApiImplicitParam(name = "user_account", value = "用户账号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "sysUser", value = "用户信息", required = false, dataType = "SysUser") })
    // @ExceptionHandler({org.springframework.beans.TypeMismatchException.class })
    @RequestMapping(value = "/", method = RequestMethod.PUT)
    public @ResponseBody ResultEntity updateUser(SysUser sysUser, String token) {
        String id = sysUser.getUserId();
        if (StringUtils.isBlank(id)) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.PARAM_ERROR);
        }
        int resultIdt = userService.updateUser(sysUser);
        if (resultIdt == -1) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.USER_NOT_EXIST);
        }
        if (resultIdt == -2) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.USER_EXIST);
        }
        if (resultIdt == -3) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.DATA_ERROR);
        }
        return new ResultEntity(ResultStatus.SUCCESS, BusinessConstant.UPDATE_SUCCESS);
    }

    @ApiOperation(value = "修改用户", notes = "修改用户信息")
    @ApiImplicitParams({ @ApiImplicitParam(name = "user_account", value = "用户账号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "sysUser", value = "用户信息", required = false, dataType = "SysUser") })
    @ExceptionHandler({ org.springframework.beans.TypeMismatchException.class })
    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    public @ResponseBody ResultEntity updateUserInfo(@RequestBody SysUser sysUser, String token) {
        String id = sysUser.getUserId();
        if (StringUtils.isBlank(id)) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.PARAM_ERROR);
        }
        int resultIdt = userService.updateUser(sysUser);
        if (resultIdt == -1) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.USER_NOT_EXIST);
        }
        if (resultIdt == -2) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.USER_EXIST);
        }
        if (resultIdt == -3) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.DATA_ERROR);
        }
        return new ResultEntity(ResultStatus.SUCCESS, BusinessConstant.UPDATE_SUCCESS);
    }

    @ApiOperation(value = "修改用户密码", notes = "修改用户密码信息")
    @ApiImplicitParams({ @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "String"),
            @ApiImplicitParam(name = "password", value = "用户新密码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "oldPassword", value = "用户旧密码", required = true, dataType = "String") })
    @RequestMapping(value = "/update/password", method = RequestMethod.PUT)
    public @ResponseBody ResultEntity updateUserPassword(PasswordVo passwordVo, String token) {
        String id = passwordVo.getUserId();
        String password = passwordVo.getPassword();
        String oldPassword = passwordVo.getOldPassword();
        if (StringUtils.isBlank(id) || StringUtils.isBlank(password) || StringUtils.isBlank(oldPassword)) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.PARAM_ERROR);
        }
        int resultIdt = userService.updateUserPassword(passwordVo);
        if (resultIdt == -1) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.USER_NOT_EXIST);
        }
        if (resultIdt == -2) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.OLD_PASSWORD_ERROR);
        }
        if (resultIdt == -3) {
            return new ResultEntity(ResultStatus.ERROR, BusinessConstant.DATA_ERROR);
        }
        return new ResultEntity(ResultStatus.SUCCESS, BusinessConstant.UPDATE_SUCCESS);
    }


    
}
